package com.huilian.iotbox.admin.service.impl;


import com.alibaba.fastjson.JSON;
import com.huilian.iotbox.admin.service.WXMessageService;
import com.huilian.iotbox.data.dto.TemplateMessage;
import com.huilian.iotbox.data.po.User;
import com.huilian.iotbox.data.properties.WeiXinProperties;
import com.huilian.iotbox.data.service.HttpService;
import com.huilian.iotbox.data.vo.DeviceBuyOrderVo;
import com.huilian.tool.common.config.WeixinConfig;
import com.huilian.tool.weixin.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class WXMessageServiceImpl implements WXMessageService {
    WeiXinProperties weiXinProperties = new WeiXinProperties();
    @Autowired
    private HttpService httpService;
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private WeixinConfig weixinConfig;

    @Override
    public void sendFaultMessage(List<String> uids, String text) {
        log.info("公众号发消息：" + uids.size());
        log.info("公众号发消息：" + uids);
        log.info("公众号发消息：" + Arrays.toString(uids.toArray()));
        log.info("公众号发消息模板id：" + weixinConfig.getMessageTemplate());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (String id : uids) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("template_id", weixinConfig.getMessageTemplate());
            jsonObject.put("touser", id);
            JSONObject data = new JSONObject();
            JSONObject item = new JSONObject();
            item.put("value", "请注意");
            item.put("color", "");
            data.put("first", item);
            item.put("value", text);
            data.put("performance", item);
            item.put("value", sdf.format(new Date()));
            data.put("time", item);
            item.put("value", "请管理人员及时处理，谢谢！");
            data.put("remark", item);
            jsonObject.put("data", data);
            log.info(JSON.toJSONString(jsonObject));
            String errmsg = call(weiXinProperties.getWX_ACCESS_TOKEN_URL(), jsonObject);
            if (!"ok".equals(errmsg)) {
                //token 失效,刷新Token重发一次
                if (errmsg.contains("access_token is invalid or not latest hint")) {
                    errmsg = call(weiXinProperties.getWX_REFUSH_ACCESS_TOKEN_URL(), jsonObject);
                    if (!"ok".equals(errmsg)) {
                        log.error("公众号验证码发送失败：{}", id);
                        throw new IllegalStateException("公众号验证码发送失败");
                    }
                }
            } else {
                log.info("公众号通知发送成功：{}", id);
            }
        }
    }

    @Override
    public void sendSmsCodeMessage(String smsCode, User user) {
        String first = "您好，" + user.getName() + "（iotBox）";
        //备注remark
        TemplateMessage tm = new TemplateMessage();
        tm.setTouser(user.getOpenId());
        tm.setTemplate_id(weiXinProperties.getSmsCodeTemplate());
        tm.getData().getFirst().setValue(first);
        tm.getData().getKeyword1().setValue(smsCode);
        tm.getData().getKeyword2().setValue("5分钟内有效");
        tm.getData().getRemark().setValue("若非本人操作，可能您的帐号存在安全风险，请及时修改密码。");
        JSONObject jsonObject = JSONObject.fromObject(tm);
        String errmsg = call2(weiXinProperties.getWX_ACCESS_TOKEN_URL(), jsonObject);
        if (!"ok".equals(errmsg)) {
            //token 失效,刷新Token重发一次
            if (errmsg.contains("access_token is invalid or not latest hint")) {
                errmsg = call2(weiXinProperties.getWX_REFUSH_ACCESS_TOKEN_URL(), jsonObject);
                if (!"ok".equals(errmsg)) {
                    log.error("公众号验证码发送失败：{}", user.getOpenId());
                    throw new IllegalStateException("公众号验证码发送失败");
                }
            }
        } else {
            log.info("公众号通知发送成功：{}", user.getOpenId());
        }
    }

    @Override
    public void sendPayMessage(DeviceBuyOrderVo deviceBuyOrderVo,String openId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TemplateMessage tm = new TemplateMessage();
        tm.setTouser(openId);
        tm.setTemplate_id(weixinConfig.getOrderMessageTemplate());
        tm.getData().getFirst().setValue("有新的一笔订单，请及时处理");
        tm.getData().getKeyword1().setValue(deviceBuyOrderVo.getOutTradeNo());
        tm.getData().getKeyword2().setValue("总购买"+deviceBuyOrderVo.getBuyCount()+"设备");
        tm.getData().getKeyword3().setValue(deviceBuyOrderVo.getTotalAmount().toString()+"元");
        tm.getData().getKeyword4().setValue(sdf.format(deviceBuyOrderVo.getCreateTime()));
//        tm.getData().getKeyword4().setValue(deviceBuyOrderVo.getAddresseeProvince()+deviceBuyOrderVo.getAddresseeCity()
//                +deviceBuyOrderVo.getAddresseeDistrict()+deviceBuyOrderVo.getAddresseeAddress());
//        tm.getData().getKeyword5().setValue(deviceBuyOrderVo.getTotalAmount().toString());
        JSONObject jsonObject = JSONObject.fromObject(tm);
        String errmsg = call(weiXinProperties.getWX_ACCESS_TOKEN_URL(), jsonObject);
        if (!"ok".equals(errmsg)) {
            //token 失效,刷新Token重发一次
            if (errmsg.contains("access_token is invalid or not latest hint")) {
                errmsg = call(weiXinProperties.getWX_REFUSH_ACCESS_TOKEN_URL(), jsonObject);
                if (!"ok".equals(errmsg)) {
                    log.error("公众号下单通知发送失败：{}", openId);
                    throw new IllegalStateException("公众号下单通知失败");
                }
            }
        } else {
            log.info("公众号通知发送成功：{}", openId);
        }
    }


    private String call2(String tokenUrl, JSONObject jsonObject) {

        JSONObject accessToken = httpService.httpGet(tokenUrl);
        log.info("accessToken.getString：{}", accessToken.getString("accessToken"));

        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/cgi-bin/message/template/send?")
                .append("access_token=").append(accessToken.getString("accessToken"));

        //发送公众号通知
        JSONObject result = httpService.httpPost(url.toString(), jsonObject.toString());
        return result.getString("errmsg");
    }

    private String call(String tokenUrl, JSONObject jsonObject) {

        String accessToken = weixinService.getAccessToken();
        log.info("accessToken.getString：{}", accessToken);

        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/cgi-bin/message/template/send?")
                .append("access_token=").append(accessToken);

        //发送公众号通知
        JSONObject result = httpService.httpPost(url.toString(), jsonObject.toString());
        System.out.println(result);
        return result.getString("errmsg");
    }
}
